package com.yt.website.action;


import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.yt.util.MD5Util;
import com.yt.website.action.base.BaseAction;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/wechat/pay")
public class WechatPayAction extends BaseAction{

    @RequestMapping("/toPay")
    public ModelAndView toPay() throws IOException {
        ModelAndView mav = new ModelAndView("WechatPay");
        String productId = "3213";
        String body = "产品1";
        String outTradeNo = "201602260101";
        String totalFee = "1";
        String notifyUrl = "http://www.yitianhealth/wechat/pay/payNotify";
        String appId = "wxc56550b08f3de65c";
        String mchId = "1317292001";
        String key = "fd7809ga0f80few8f9ewq0vjdJKLFDSF";

        Map<String, String> paramMap = Maps.newTreeMap();
        paramMap.put("trade_type", "NATIVE"); //交易类型
        paramMap.put("spbill_create_ip",localIp()); //本机的Ip
        paramMap.put("product_id", productId); // 商户根据自己业务传递的参数 必填
        paramMap.put("body", body);         //描述
        paramMap.put("out_trade_no", outTradeNo); //商户 后台的贸易单号
        paramMap.put("total_fee", "" + totalFee); //金额必须为整数  单位为分
        paramMap.put("notify_url", notifyUrl); //支付成功后，回调地址
        paramMap.put("appid", appId); //appid
        paramMap.put("mch_id", mchId); //商户号
        paramMap.put("nonce_str", "1234");  //随机数
        paramMap.put("device_info", "WEB");
        StringBuilder sb =new StringBuilder();
        Joiner.on("&").withKeyValueSeparator("=").appendTo(sb, paramMap);
        System.out.println(sb.toString());
        String sign = MD5Util.MD5(sb.append("&key=").append(key).toString());

        paramMap.put("sign", sign.toUpperCase());

        StringBuilder xml = new StringBuilder();
        xml.append("<xml>");

        for(String k : paramMap.keySet()){
            xml.append("<").append(k).append(">").append(paramMap.get(k)).append("</").append(k).append(">");
        }
        xml.append("</xml>");
        System.out.println(xml.toString());
        org.apache.http.client.HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder");
        StringEntity entity = new StringEntity(xml.toString(), "UTF-8");
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String str = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(str);
        return mav;
    }

    private static String localIp() {
        String ip = null;
        Enumeration allNetInterfaces;
        try {
            allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
                for (InterfaceAddress add : InterfaceAddress) {
                    InetAddress Ip = add.getAddress();
                    if (Ip != null && Ip instanceof Inet4Address) {
                        ip = Ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
        }
        return ip;
    }

    @RequestMapping("/qrcode")
    public void qrcode(@RequestParam(value="content", required=true) String content,
                       HttpServletResponse response) {

        MultiFormatWriter writer = new MultiFormatWriter();
        Map hints = new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix bitMatrix = null;
        try {
            bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, 300, 300, hints);
            BufferedImage image = toBufferedImage(bitMatrix);
            ImageIO.write(image, "png", response.getOutputStream());
        }catch(Exception ex){}
    }

    private static BufferedImage toBufferedImage(BitMatrix bitMatrix){
        int WHITE = 0xFFFFFFFF;
        int BLACK = 0x00000000;
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for(int x=0; x<width; x++){
            for(int y=0; y<height; y++){
                image.setRGB(x, y, bitMatrix.get(x, y) ?BLACK:WHITE);
            }
        }
        return image;
    }
}
